//
//  StaffAuditorViewController.m
//  NtoccShipper
//
//  Created by 张天兴 on 2024/11/11.
//  Copyright © 2024 zhuchongjin. All rights reserved.
//

#import "StaffAuditorViewController.h"
#import "StaffAuditorTableViewCell.h"
#import "SourcesOrderListModel.h"
#import "StaffConfirmViewController.h"
@interface StaffAuditorViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) CJTableView *tableView;
@property (nonatomic,strong) NSMutableArray *modelArray;
@property (nonatomic,strong) NSString *refreshType; //刷新
@property (nonatomic,readwrite) int page;
@property (nonatomic,strong) NSString *strStatus;
@property (nonatomic, strong) CJButton * consolidatedButton;
@property (nonatomic, strong) NSString *strTitle;

@end

@implementation StaffAuditorViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.modelArray removeAllObjects];
    [self.consolidatedButton setTitle:@"批量核算（0）个运单" forState:(UIControlStateNormal)];
    [self downRefresh];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitleName:CJLString(@"批量核算")];
    [self setBackLeftButton:@""];
    self.strTitle = @"";
    WS(ws);
    self.tableView.placeHolderView = [[KKTableViewNoDataView alloc] initWithFrame:self.tableView.bounds image:[UIImage imageNamed:@"no_data"] viewClick:^{
           [ws.tableView.mj_header beginRefreshing];
    }];
    [self.tableView registerNib:[UINib nibWithNibName:@"StaffAuditorTableViewCell" bundle:nil] forCellReuseIdentifier:@"StaffAuditorTableViewCell"];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.consolidatedButton];
    [self initData];
}

- (void)initData{
    self.modelArray = [[NSMutableArray alloc]init];
    self.page = 1;
}

/// <#Description#>
- (void)loadData {
//    @[@"全部",@"未接单",@"已接单",@"已装货",@"已卸货",@"已核算",@"已完成""]
        self.strStatus = @"3";
    
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderDetail",CJBaseUrl);
    NSDictionary *dicPar = @{
        @"pageNum":CJStringWithFormat(@"%d",self.page),
         @"pageSize":@"8",
         @"status":self.strStatus,
         @"mainOrderCode":self.strCode,
    };

    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {

        DLog(@"++++++++%@",responseObject);
        NSArray *list = responseObject[@"records"];
        NSDictionary *dicSum = responseObject[@"sumObject"];

        
//            if (list.count > 0) {

            if ([ws.refreshType isEqualToString:@"down"]) {
                [ws.modelArray removeAllObjects];
            }

            NSError * error ;
            NSArray *arr = [SourcesOrderListModel arrayOfModelsFromDictionaries:list error:&error];
            [ws.modelArray addObjectsFromArray:arr];
  
            [ws.tableView.mj_header endRefreshing];
            [ws.tableView.mj_footer endRefreshing];

        if (ws.modelArray.count == [responseObject[@"total"] intValue]) {
                [ws.tableView.mj_footer endRefreshingWithNoMoreData];
            }

        [ws.tableView reloadData];
    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        [ws.tableView.mj_header endRefreshing];
        [ws.tableView.mj_footer endRefreshingWithNoMoreData];
    }];


}

- (void)dealloc{
    CJRemoveNofify;
}

- (void)downRefresh{
    self.refreshType = @"down";
    self.page = 1;
    [self loadData];
}

- (void)upRefresh{
    self.refreshType = @"up";
    self.page ++;
    [self loadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 165;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *identifier = @"StaffAuditorTableViewCell";
    StaffAuditorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell ConsolidatePaymentCellfuzhi:self.modelArray[indexPath.row]];
    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SourcesOrderListModel *model = self.modelArray[indexPath.row];
    if ([model.isSelected isEqualToString:@"1"]) {
        model.isSelected = @"0";
    }else{
        model.isSelected = @"1";
    }
    [self.tableView reloadRow:indexPath.row inSection:0 withRowAnimation:(UITableViewRowAnimationNone)];
    int numberStr = 0;
    for (SourcesOrderListModel *model1 in self.modelArray) {
        if ([model1.isSelected isEqualToString:@"1"]) {
            numberStr += 1;
        }
    }
    [self.consolidatedButton setTitle:CJStringWithFormat(@"批量核算（%d）个运单",numberStr) forState:(UIControlStateNormal)];
}
- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, CJTableToTopHeight + kTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight - kNavBarHeight -CJTableToTopHeight - 30),UITableViewStylePlain)
        .tbDelegate(self)
        .tbDataSource(self)
        .tbSetOther(YES)
        .tbEstimatedRowHeight(YES)
        .tbMjHeadFooter(YES)
        ;
        WS(ws);
        _tableView.blockMjHeader = ^(BOOL isheader) {
            if (isheader) {
                [ws downRefresh];
            } else {
                [ws upRefresh];
            }
        };
    }
    return _tableView;
}
- (CJButton *)consolidatedButton{
    if (!_consolidatedButton) {
        _consolidatedButton = CJButton.btnInit
        .btnFrame(CGRectMake(50,CGRectGetMaxY(self.tableView.frame) + 10,SCREEN_WIDTH - 100,50))
        .btnText(@"批量核算(0)个运单")
        .btnNormalTitleColor([UIColor cjWhiteColor])
        .btnBgColor([UIColor cjMainColor])
        .btnTargetAction(self, @selector(btnCancleAction:))
        .btnCornerRadius(10)
        .btnCornerWidth(1)
        .btnCornerColor([UIColor cjMainColor])
        ;
    }
    return _consolidatedButton;
}
- (void)btnCancleAction:(UIButton *)btn{
    NSString * orderDetailCodes = @"";
    int number = 0;
    for (SourcesOrderListModel *model in self.modelArray) {
        if ([model.isSelected isEqualToString:@"1"]) {
            orderDetailCodes = CJStringWithFormat(@"%@,%@",orderDetailCodes,model.code);
            number += 1;
        }
    }
    if (number == 0) {
        [CJAlert showStringDismissWithDelay:@"请先选择运单，再核算"];
        return;
    }else{
        SourcesOrderListModel *modelAll = self.modelArray.firstObject;
        NSMutableArray *arr = [@[] mutableCopy];
        for (SourcesOrderListModel *model in self.modelArray) {
            if ([model.isSelected isEqualToString:@"1"]) {
                [arr addObject:model];
            }
        }
        int sum = 0;
        for (SourcesOrderListModel *model in arr) {
            if (![modelAll.mainOrderNumber isEqualToString:model.mainOrderNumber]) {
                sum += 1;
            }
        }
        if (sum != 0) {
            [CJAlert showStringDismissWithDelay:@"请选择同货源的运单，再核算"];
            return;
        }else{
            orderDetailCodes = [orderDetailCodes substringFromIndex:1];
            StaffConfirmViewController *vc = [[StaffConfirmViewController alloc] init];
            vc.orderDetailCodes = orderDetailCodes;
            [self pushVc:vc];
        }
       

    }
  
}

@end
